import appConfig from './appConfig';
import Taro from '@tarojs/taro';
export const defaultAvatar = `https://fulu-media.oss-cn-hangzhou.aliyuncs.com/movie/assets/theme/img/default_avatar.png`;
export const defaultNickName = `福禄影迷`;
import { getProductInfoById, submitOrder } from '@/service';
import { useUserStore } from '@/common/hox/userStore';

// 判断是否为微信浏览器环境
export function inWechat() {
    return (
        process.env.TARO_ENV == 'weapp' ||
        (process.env.TARO_ENV == 'h5' &&
            /micromessenger/i.test(window.navigator.userAgent.toLowerCase()))
    );
}

export const shareParam = {
    get title() {
        return `${appConfig.programTitle}`;
    },
    link: process.env.TARO_ENV == 'h5' ? `${window.location.origin}/` : '',
    desc: '',
    // todo 三方小程序LOGO
    imgUrl: defaultAvatar,
};

// 点击banner 跳转逻辑
export const bannerJump = async (item: Banner.List) => {
    const tabPages = [
        '/pages/movie/index',
        '/pages/index/index',
        '/pages/my/index',
        '/pages/order/index',
    ];

    if (tabPages.includes(item.jumpLink.split('?')[0])) {
        Taro.switchTab({ url: item.jumpLink });
        return;
    }
    if (item.jumpLink) {
        if (process.env.TARO_ENV == 'weapp' && item.jumpType == 1) {
            item.appId &&
                Taro.navigateToMiniProgram({
                    appId: item.appId,
                    path: item.jumpLink,
                });
            return;
        }
        Taro.navigateTo({
            url: item.jumpLink,
        });
    } else {
        const { jumpProductId = null } = item;

        if (!jumpProductId) {
            return;
        }

        const productInfo = await getProductInfoById(jumpProductId);
        if (!productInfo) {
            return;
        }

        const { brandType, productId } = productInfo;

        if (brandType === 1) {
            Taro.navigateTo({
                url: `/pages/movie/theaterList/index?movieId=${productId}`,
            });
        }
    }
};

export const formatFilmPhoto = (url: string) => {
    const identifier = /[0-9]{3,}x[0-9]{3,}/; //正则匹配 3位整数 x 3位整数
    const isCuttedImg = identifier.test(url); //验证是否是裁剪过的图片
    if (url && url.includes('gw.alicdn.com') && !isCuttedImg) {
        return `${url}_300x300.jpg`;
    }
    return url;
};

type PaymentResponse = {
    orderNo: string;
    paymentAmount: number;
    productName: string;
    sign: string;
    timestamp: string;
    openId: string;
    channel: string;
    checkOutUrl: string;
    checkOutApp: string;
};
// 支付 （代理）
export const openPay = (res: PaymentResponse): void => {
    if (!res) {
        console.error('Payment response is missing');
        return;
    }

    try {
        const urlParam = Taro.getStorageSync('open_url_param') || {};
        const paymentParams = {
            ctOrderId: res.orderNo,
            payPrice: res.paymentAmount,
            productName: res.productName,
            sign: res.sign,
            timestamp: res.timestamp,
            uid: res.openId,
            channel: res.channel,
            ej: urlParam.ej ? encodeURIComponent(urlParam.ej) : null,
        };

        if (urlParam.ct === '1') {
            // 公众号跳转收银台
            if (!res.checkOutUrl) {
                throw new Error('Checkout URL is missing');
            }
            const url = new URL(res.checkOutUrl);
            Object.entries(paymentParams).forEach(([key, value]) => {
                if (value) url.searchParams.append(key, String(value));
            });
            (window.parent || window).location.href = url.toString();
        } else {
            // 小程序跳转收银台
            if (!res.checkOutApp) {
                throw new Error('Checkout App URL is missing');
            }
            const obj = encodeURIComponent(JSON.stringify(paymentParams));
            wx.miniProgram.navigateTo({ url: `${res.checkOutApp}?obj=${obj}` });
        }
    } catch (error) {
        console.error('Payment redirection failed:', error);
        Taro.showToast({ title: '支付跳转失败，请重试', icon: 'none' });
    }
};


// 支付 (自营)
export const pay = (res) => {
    if (!res?.orderNo && res?.orderNo === undefined) return;
    const linkToOrderPage = () =>
        Taro.redirectTo({
            url: '/pages/order/detail/index?orderNo=' + res.orderNo,
        });
    const complete = () => {
        setTimeout(linkToOrderPage, 1000);
    };
    if (!res?.paymentAmount) {
        complete();
    } else {
        // 自营支付
        payment({
            orderNo: res.orderNo,
            complete,
        });
    }
};


/**
 * @description 支付
 * @param  orderNo 订单号 
 * @returns 
 */
export async function payment(payParameter: { orderNo: string; complete: () => void }) {
    try {
        const res = await submitOrder(payParameter.orderNo);
        if (res.payParameter.includes('http')) {
            const url = res.payParameter;
            if (!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
                return (window.location.href = url.replace(/&?redirect_url=[^&]*/, ''));
            }
            return (window.location.href = url);
        }
        const params = JSON.parse(res.payParameter);
        if (process.env.TARO_ENV == 'weapp') {
            Taro.requestPayment({
                ...params,
                success: () => {
                    setTimeout(() => {
                        Taro.hideLoading();
                    }, 1000);
                },
                fail: () => {
                    setTimeout(() => {
                        Taro.hideLoading();
                    }, 1000);
                },
                complete: () => {
                    payParameter.complete();
                },
            });
        }
        if (process.env.TARO_ENV == 'h5') {
            //const { userInfo } = useUserStore();
            Taro.hideLoading();
            // const isOpenPurchase = userInfo?.purchaseType !== 1;
            wx.chooseWXPay({
                ...params,
                timestamp: params.timeStamp,
                success: () => {
                    setTimeout(() => {
                        Taro.hideLoading();
                    }, 1000);
                },
                fail: () => {
                    setTimeout(() => {
                        Taro.hideLoading();
                    }, 1000);
                },
                complete: () => {
                    payParameter.complete();
                },
            });
        }
    } catch (error) {

    }
}
